package com.zim.aliot.schedules;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.zim.aliot.async.NotifyCommand;
import com.zim.aliot.dataobject.CommandDo;
import com.zim.aliot.util.RedisLockUtils;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class AckNotify {
    @Autowired
    private MongoTemplate mongoTemplate;
    
	@Autowired
	private RedisLockUtils redisLockUtils;
	
	@Autowired
	private NotifyCommand notifyCommand;

	@Scheduled(cron = "0 0/1 * * * *") 
    public void ackNotify() {
		long time = System.currentTimeMillis()+60000;
		if(!redisLockUtils.lock("acknotify", String.valueOf(time))) {
		    log.warn("[acknotify]被锁");
		    return;
		}
		Criteria criteria  = Criteria.where("time").lt(System.currentTimeMillis()-600000).and("push").is(0);
		List<CommandDo> commandDo= mongoTemplate.find(new Query(criteria), CommandDo.class);
		if(null != commandDo && !commandDo.isEmpty()) {
			for(CommandDo command:commandDo) {
				if(("LOCK").equals(command.getCommand()) || ("IGNITE").equals(command.getCommand()) || ("WHISTLE").equals(command.getCommand())) {
					notifyCommand.ackNotify(command.getVin(), command.getCommand(), command.getSerialNumber(), false, "网络超时");
				}else if (("BLUETOOTH").equals(command.getCommand())) {
					notifyCommand.bluePassNotify(command.getVin(), command.getCommand(), command.getSerialNumber(), false);
				}else {
					log.warn("[acknotify]其它指令");
				}
			}
		}
	}
}
